package cn.b.sky.user;

import cn.b.sky.common.utils.AjaxUtil;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class BskyLoginUrlEntryPoint extends LoginUrlAuthenticationEntryPoint {

  private static final Logger log= LoggerFactory.getLogger(BskyLoginUrlEntryPoint.class);


  public BskyLoginUrlEntryPoint(String loginFormUrl) {
    super(loginFormUrl);
  }

  /**
   * (非 Javadoc) Title: commence Description: 不考虑https的实现。
   * 
   * @param request
   * @param response
   * @param authException
   * @throws IOException
   * @throws ServletException
   * @see org.springframework.security.web.AuthenticationEntryPoint#commence(javax.servlet.http.HttpServletRequest,
   *      javax.servlet.http.HttpServletResponse,
   *      org.springframework.security.core.AuthenticationException)
   */
  @Override
  public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
      throws IOException, ServletException {

    String url = request.getRequestURI();

    if (log.isDebugEnabled()) {
      log.debug("url:" + url);
    }
    // 非ajax请求
    boolean isAjax = AjaxUtil.isAjax(request);
    if (!isAjax) {
      super.commence(request, response, authException);
    } else {
      // ajax请求，返回json，替代redirect到login page
      if (log.isDebugEnabled()) {
        log.debug("ajax request or post");
      }

      response.setHeader("Content-Type", "application/json;charset=UTF-8");
      response.setContentType("application/json;charset=UTF-8");
      /**
       * 调用dwz的超时返回状态
       * 
       * @author lidapeng
       */
      String jsonObject = JSONObject.toJSONString(AjaxUtil.ajaxTimeout(null));
      PrintWriter out = response.getWriter();
      out.print(jsonObject);
      out.flush();
      out.close();
    }
  }

}
